package com.walter.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.RuntimeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author ：ch
 * @date ：Created in 2021/5/25
 * @description：
 * @modified By：
 * @version: 1.0
 */
@Service
@Slf4j
public class SystemService {
    @Value("${backupDBPath}")
    private String backupDBPath;

    @Value("${spring.datasource.url}")
    private String url;

    @Value("${spring.datasource.username}")
    private String username;

    @Value("${spring.datasource.password}")
    private String password;

    // backup数据库 linux测试 todo
    public Boolean backupDB(){
        String time = DateUtil.format(new Date(),"yyyyMMddHHmmss");
        String fileName = "backupDB" + time + ".sql";
        String absolutePath = backupDBPath + fileName;
        if (!FileUtil.exist(backupDBPath))
            FileUtil.mkdir(backupDBPath);
        String DB = url.split(ReUtil.escape('?'))[0].split(ReUtil.escape('/'))[3]; // 数据库名称
        // String command = "mysqldump " + DB + " -u" + username + " -p" + password + "  --result-file=" + absolutePath;
        String command = "mysqldump " + "-h101.132.242.186 " + "-P3306" + " -u" + username + " -p" + password + " " + DB
                + "  --result-file=" + absolutePath; // todo
        String retVal = RuntimeUtil.execForStr(command);
        log.info("mysqldump DB base, return is {}",retVal);
        return true;
    }
}
